class_name UnitCard
extends Button

# ===============================================

signal unit_bought(unit: UnitStats)

# ===============================================

@export var player_stats: PlayerStats
@export var sfx: AudioStream

@export var unit_stats: UnitStats :
	set(value):
		unit_stats = value
		if not is_instance_valid(empty_placeholder):
			return
		
		if not unit_stats:
			empty_placeholder.show()
			disabled = true
			bought = true
			return
		
		border_color = UnitStats.RARITY_COLORS[unit_stats.rarity]
		border_sb.border_color = border_color
		bottom_sb.bg_color = border_color
		gold_cost.text = str(unit_stats.get_gold_cost())
		unit_name.text = unit_stats.name
		unit_icon.texture.region.position = Vector2(unit_stats.skin_coordinates) * Arena.CELL_SIZE
		traits.text = "\n".join(Trait.get_trait_names(unit_stats.traits))
		
		disabled = player_stats.gold < unit_stats.get_gold_cost()
		if not disabled or bought:
			modulate = Color(Color.WHITE, 1.0)
		else:
			modulate = Color(Color.WHITE, 0.5)

# ===============================================

const HOVER_BORDER_COLOR: Color = Color("fafa82")

@onready var traits: Label = $BackDrop/Traits
@onready var unit_name: Label = $Bottom/MarginContainer/HBoxContainer/UnitName
@onready var bottom: Panel = $Bottom
@onready var gold_cost: Label = $Bottom/MarginContainer/HBoxContainer/GoldContainer/GoldCost
@onready var border: Panel = $Border
@onready var unit_icon: TextureRect = $UnitIcon
@onready var empty_placeholder: Panel = $EmptyPlaceholder
@onready var border_sb: StyleBoxFlat = border.get_theme_stylebox("panel")
@onready var bottom_sb: StyleBoxFlat = bottom.get_theme_stylebox("panel")

# ===============================================

var bought: bool = false
var border_color: Color

# ===============================================

func __on_player_stats_changed() -> void:
	if not unit_stats:
		return
	
	disabled = player_stats.gold < unit_stats.get_gold_cost()
	if not disabled or bought:
		modulate = Color(Color.WHITE, 1.0)
	else:
		modulate = Color(Color.WHITE, 0.5)

# ===============================================

func _ready() -> void:
	player_stats.changed.connect(__on_player_stats_changed)
	__on_player_stats_changed()


func _on_pressed() -> void:
	if bought:
		return
	bought = true
	empty_placeholder.show()
	player_stats.gold -= unit_stats.get_gold_cost()
	unit_bought.emit(unit_stats)
	SFXPlayer.play(sfx)


func _on_mouse_entered() -> void:
	if not disabled:
		border_sb.border_color = HOVER_BORDER_COLOR


func _on_mouse_exited() -> void:
	border_sb.border_color = border_color
